package reviewAlgorithms.search;

import java.util.Arrays;

public class Solve {
    public static void main(String[] args) {
        char[][] board = {
                {'O','O','O','O','X','X'},
                {'O','O','O','O','O','O'},
                {'O','X','O','X','O','O'},
                {'O','X','O','O','X','O'},
                {'O','X','O','X','O','O'},
                {'O','X','O','O','O','O'}
        };
        solve(board);
        for (int i = 0; i < board.length; i++) {
            System.out.println(Arrays.toString(board[i]));
        }
    }
    public static void solve(char[][] board) {
        if (board == null || board.length < 1){
            return;
        }
        int rowNum = board.length;
        int columnNum = board[0].length;
        int maxNum = rowNum*columnNum;
        int[][] state = new int[rowNum][columnNum];
        for (int i = 0; i < maxNum; i++) {
            int row = i / columnNum;
            int column = i % columnNum;
            if (board[row][column] == 'O' && state[row][column] == 0 && isContain(row,column,state,board)){
                solveContain(row,column,board);
            }
        }
    }

    private static void solveContain(int row, int column, char[][] board) {
        if (row < 0 || row >= board.length || column < 0 || column >= board[0].length){
            return;
        }

        if (board[row][column] == 'X'){
            return;
        }

        if (board[row][column] == 'O'){
            board[row][column] = 'X';
            solveContain(row - 1,column,board);
            solveContain(row + 1,column,board);
            solveContain(row,column - 1,board);
            solveContain(row ,column + 1,board);
        }
    }

    private static boolean isContain(int row, int column, int[][] state, char[][] board) {
        if (row < 0 || column < 0 || row >= board.length || column >= board[0].length){
            return false;
        }
        boolean flag = true;
        boolean temp;
        if (board[row][column] == 'O' && state[row][column] == 0){
            state[row][column] = 1;
            flag = isContain(row - 1,column,state,board);

            temp = isContain(row + 1,column,state,board);
            flag = flag && temp;

            temp = isContain(row,column - 1,state,board);
            flag = flag && temp;

            temp = isContain(row,column + 1,state,board);
            flag = flag && temp;
        }
        return flag;
    }
}
